import {toastCallBack} from "@/utils/toast";

// 不需要token接口名单
const whiteList = ["/wx/user/wxa6b3fbc130f00be6/wechat/login", "/wx/user/wxa6b3fbc130f00be6/wechat/binding", "/wx/user/wxa6b3fbc130f00be6/web/login"];
// 可以从外部引入baseURL,也可以定义到config下的baseURL中
const notErrList = [];
export default {
  config: {
    baseURL: "https://www.saaslndx.com/prod-api",
    // 处理token的方法
    getToken() {
      try {
        const token = uni.getStorageSync('token');
        // const loginStoreJson = uni.getStorageSync('loginStore');
        // const loginStore = JSON.parse(loginStoreJson);
        // console.log(loginStoreJson, 'loginStoreJson', loginStore);
        // const token = loginStore.userInfo.token;
        const currentPages = getCurrentPages();
        const currentRoute = currentPages[currentPages.length - 1].route;
        if (!token && currentRoute !== 'pages/login/index') {
          return uni.reLaunch({
            url: '/pages/login/index',
          });
        }
        return `Bearer ${token}`;
      } catch (err) {
        console.log(err, 'err');
      }
    },
    // 请求拦截器
    beforeRequest(opts = {}) {
      const options = JSON.parse(JSON.stringify(opts))
      return new Promise((resolve) => {
        if (!whiteList.includes(options.url)) {
          // 封装自己的请求头
          options.header = {
            ...options.header,
            Authorization: this.getToken()
          };
        }
        if (options.baseURL) {
          options.url = options.baseURL + options.url;
        } else {
          options.url = this.baseURL + options.url;
        }
        options.method = options.method.toUpperCase() || 'GET';
        resolve(options);
      });
    },
    // 响应拦截器
    handleResponse(res, options) {
      console.log(res, 'handleResponse');
      return new Promise((resolve, reject) => {
        // 处理错误
        const msg = res.data.msg || '请求错误';
        if (res && res.statusCode !== 200) {
          !notErrList.includes(options.url) && uni.showToast({
            icon: 'none',
            title: msg,
          });
          return reject(res.data);
        }
        if (res.data.code !== 200) {
          // if (!notErrList.includes(options.url)) {
          //   toastCallBack(msg, 'none', () => {
          //     return reject(res.data);
          //   });
          // } else {
          // 登录过期
          if (res.data.code === 401) {
            uni.navigateTo({
              url: '/pages/login/index'
            });
          }
        }
        //   return reject(res.data);
        //   // }
        // } else {
        return resolve(res.data);
        // }
      });
    },
  },
  // request 请求
  request(options = {}) {
    return this.config
      .beforeRequest(options)
      .then((opt) => {
        return uni.request(opt);
      })
      .then((res) => {
        return this.config.handleResponse(res, options);
      });
  },
};
